'use client';

import { queryMenuRolesById } from '@/services/api';
import { useQuery } from '@tanstack/react-query';

import type { IRole } from '@/interfaces';
import Alert from '@/app/[locale]/alert/alert';

export default function RolesMenuAdminPage({ id }: { id: number }) {
  const queryMenuRolesByIdQuery = useQuery(
    ['/menus', id, '/roles'],
    async (context) => {
      return (await queryMenuRolesById({
        id: context.queryKey[1] + '',
      })) as IRole[];
    },
    {
      enabled: !!id,
    },
  );

  if (queryMenuRolesByIdQuery.data) {
    const data = queryMenuRolesByIdQuery.data;
    return (
      <div className="card">
        <div className="card-header bg-transparent text-muted">
          <i className="bi bi-bookmarks me-2"></i>
          角色
        </div>

        <div className="card-body">
          <div className="table-responsive">
            <table className="table table-hover align-middle">
              <thead>
                <tr className="text-nowrap">
                  <th scope="col" className="w-10">
                    ID
                  </th>
                  <th scope="col" className="w-10">
                    名称
                  </th>
                </tr>
              </thead>
              <tbody>
                {data.map((item) => {
                  return (
                    <tr key={item.id} className="text-nowrap">
                      <td>{item.id}</td>
                      <td>{item.name}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {data.length === 0 && (
            <div className="mt-2 mb-4 text-center text-muted">暂无角色</div>
          )}
        </div>
      </div>
    );
  }

  if (queryMenuRolesByIdQuery.error) {
    return <Alert type="error" message={queryMenuRolesByIdQuery.error} />;
  }

  return (
    <div className="card">
      <div className="card-body text-center">
        <span
          className="spinner-border spinner-border-sm"
          role="status"
          aria-hidden="true"
        ></span>
      </div>
    </div>
  );
}
